<template>
  <!-- 加载器 -->
  <Loading v-if="isLoading"></Loading>
  <Form
    class="w-1/3 m-auto mt-40 shadow-2xl shadow-red-300 rounded-box p-10"
    v-if="!isLoading"
    :validation-schema="schema"
    @submit="onSubmit"
  >
    <!-- student ID -->
    <!-- <div class="flex gap-2 my-2 mx-auto pt-2"> -->
    <label class="input flex gap-2 w-3/4 mx-auto mt-2"
      >Name
      <Field
        name="name"
        type="text"
        class="input input-primary"
        v-model="name"
      />
    </label>
    <ErrorMessage name="name" class="text-red-500 text-sm block text-center" />
    <!-- </div> -->
    <label class="input flex gap-2 my-2 w-3/4 mx-auto"
      >Email
      <Field
        name="email"
        type="text"
        class="input input-primary"
        v-model="email"
      />
    </label>
    <ErrorMessage name="email" class="text-red-500 text-sm block text-center" />
    <!-- 班级 -->
    <Field name="classInfo" v-slot="{ field }">
      <select v-bind="field" class="select flex gap-2 my-2 w-3/4 mx-auto">
        <option disabled value="">Choose Class</option>
        <option
          v-for="(item, index) in classInChargeArr"
          :key="index"
          :value="item"
        >
          Class {{ item.split("|")[0] }}|Grade {{ item.split("|")[1] }}
        </option>
      </select>
      <ErrorMessage
        name="classInfo"
        class="text-red-500 text-sm block text-center"
      />
    </Field>

    <!-- 性别 -->
    <Field name="gender" v-slot="{ field }">
      <select v-bind="field" class="select flex gap-2 my-2 w-3/4 mx-auto">
        <option disabled value="">Choose Gender</option>
        <option value="male">male</option>
        <option value="female">female</option>
      </select>

      <ErrorMessage
        name="gender"
        class="text-red-500 text-sm block text-center"
      />
    </Field>
    <!-- 按钮 -->
    <div class="text-center">
      <button class="btn btn-primary">Add Student</button>
    </div>
  </Form>
</template>
<script setup>
import { createStudent } from "@/services/ApiStudent";
import { getTeacherByTeacherId } from "@/services/apiTeacher";
import { getConfig } from "@/ultils/configHelper";
import { useRouter } from "vue-router";
import { ref, onMounted } from "vue";
import { signup } from "@/services/ApiAuth";
import { useToast } from "vue-toastification";
import Loading from "@/ui/Loading.vue";

import { Form, Field, ErrorMessage } from "vee-validate";
import * as yup from "yup";

const schema = yup.object({
  name: yup
    .string()
    .required()
    .min(2)
    .notOneOf(["username"], "Name cannot be called username"),
  email: yup
    .string()
    .required()
    .email()
    .notOneOf(["example@example.com"], "Please enter a valid email address"),
  classInfo: yup.string().required("Please select a class"),
  gender: yup
    .string()
    .required("Please select a gender")
    .oneOf(["male", "female"]),
});

const isLoading = ref(true);

const toast = useToast();

const router = useRouter();
const name = ref("username");
const email = ref("example@example.com");
const classInfo = ref("");
const gender = ref("");

const classInChargeArr = ref([]);

const teacherData = ref({});

onMounted(async () => {
  isLoading.value = true;
  const tokenName = getConfig("SUPABASE_AUTH_TOKEN");
  teacherData.value = JSON.parse(localStorage.getItem(tokenName));
  const classes = await getTeacherByTeacherId(teacherData.value.user.id);
  classInChargeArr.value = JSON.parse(classes[0].class_in_charge);
  console.log(classInChargeArr.value);
  isLoading.value = false;
});

async function onSubmit(values) {
  toast.info("Creating a student...");
  //create a user
  const userData = await signup(email.value, "123456", {
    isStudent: true,
  });
  const userId = userData.user.id;
  // insert a student
  const data = await createStudent({
    name: name.value,
    class: values.classInfo.split("|")[0], // 注意这里应该是班级而不是年级
    grade: values.classInfo.split("|")[1],
    gender: values.gender,
    teacher_id: teacherData.value.user.id,
    avatar:
      "https://gykfmvjuroywaelyraez.supabase.co/storage/v1/object/public/avatar/public/640318170@qq.com-1757502395373",
    student_id: userId,
  });
  console.log("have create a student:");
  console.log(data);

  router.push("/home/student");

  toast.success("Create a student successfully");
}
</script>
